//
//  JPSettingVC.m
//  JPKY
//
//  Created by Vitas on 2016/11/13.
//  Copyright © 2016年 Vitas. All rights reserved.
//

#import "JPSettingVC.h"
#import "JPSettingModel.h"
#import "JPSettingOpinionVC.h"
#import "JPSettingAlterSecretVC.h"
#import <SVProgressHUD.h>
#import <SDImageCache.h>

static NSString *leftBarSettingCellReuseID = @"leftBarSettingCellReuseID";

@interface JPSettingVC ()<UITableViewDataSource,UITableViewDelegate>

// 设置界面
@property (weak,nonatomic)UITableView *settingView;
// 数据模型数据
@property (copy,nonatomic)NSArray <JPSettingModel *> *settings;

@end

@implementation JPSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // 加载数据
    [self loadPlist];
    
    // 创建tableView界面
    UITableView *settingView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.settingView = settingView;
    [self.view addSubview:settingView];
    // 设置代理数据源
    self.settingView.dataSource = self;
    self.settingView.delegate = self;
    // 注册cell
    [self.settingView registerClass:[UITableViewCell class] forCellReuseIdentifier:leftBarSettingCellReuseID];
}


/**
 读取数据
 */
- (void)loadPlist {
    
    NSArray *dictArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"leftBarSettingCellPList.plist" ofType:nil]];
    
    NSMutableArray *modelArrM = [NSMutableArray array];
    for (NSDictionary *dict in dictArr) {
        JPSettingModel *settingModel = [JPSettingModel settingModelWithDict:dict];
        [modelArrM addObject:settingModel];
    }
    self.settings = modelArrM.copy;
}

#pragma mark - UITableViewDataSource 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.settings.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftBarSettingCellReuseID];
    
    // 给cell赋值
    cell.textLabel.text = self.settings[indexPath.row].title;
    [cell.imageView setImage:[UIImage imageNamed:self.settings[indexPath.row].icon]];
    UIImageView *rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"position-right"]];
    [rightView sizeToFit];
    cell.accessoryView = rightView;
    
    return cell;
}

#pragma mark - UITableViewDelegate 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
            
        case 0:
            // 意见反馈
        {
            JPSettingOpinionVC *vc = [[JPSettingOpinionVC alloc] init];
            vc.navigationItem.title = @"意见反馈";
            // 页面跳转
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
            // 加符号说明
        {
            JPSettingOpinionVC *vc = [[JPSettingOpinionVC alloc] init];
            vc.navigationItem.title = @"加符号说明";
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:
            //修改密码
        {
            JPSettingAlterSecretVC *vc = [[JPSettingAlterSecretVC alloc] init];
            vc.navigationItem.title = @"修改密码";
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3:
            // 清除缓存
            [self cleanCacheAction];
            break;
        case 4:
            // 注销用户
            [self logoutAction];
            break;
        default:
            break;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - 设置界面的点击事件
/**
 注销
 */
- (void)logoutAction {
    
    // 创建一个alert控制器
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要注销吗?" preferredStyle:UIAlertControllerStyleActionSheet];
    // 添加注销点击事件
    [alert addAction:[UIAlertAction actionWithTitle:@"注销" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"logoutSuccess" object:nil];
    }]];
    // 添加取消点击事件
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    // 弹出提示框
    [self presentViewController:alert animated:YES completion:nil];
}

/**
 清理缓存主方法
 */
- (void)cleanCacheAction {
    
    // 计算病例缓存
    unsigned long long cacheSize = [SDImageCache sharedImageCache].getSize;
    // 计算SD图片缓存
    // 病例缓存地址
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *illnessCasePath = [paths stringByAppendingPathComponent:@"illness"];
    // 获取病例加图片的缓存大小
    cacheSize += [self getFileSizeWith:illnessCasePath];
    // 设置文件大小格式
    NSString *sizeText = [self setFileSizeFormatWith:cacheSize];
    // 创建一个alert控制器
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您确定要清除缓存吗?" message:[NSString stringWithFormat:@"缓存大小: %@",sizeText] preferredStyle:UIAlertControllerStyleActionSheet];
    // 添加注销点击事件
    [alert addAction:[UIAlertAction actionWithTitle:@"清理" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 移除图片缓存
        [[SDImageCache sharedImageCache] cleanDisk];
        // 移除病例缓存
        [self cleanCacheAtPath:illnessCasePath];

        // 弹窗提示
        [SVProgressHUD setMinimumDismissTimeInterval:1.0];
        [SVProgressHUD showSuccessWithStatus:@"清理成功!"];
    }]];
    // 添加取消点击事件
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    // 弹出提示框
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 清除缓存相关
/**
 获取文件大小对应的文本格式
 */
- (NSString *)setFileSizeFormatWith:(long long)size {
    
    NSString *sizeText = nil;
    if (size >= pow(10, 9)) {
        sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
    }else if (size >= pow(10, 6)) {
        sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
    }else if (size >= pow(10, 3)) {
        sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
    }else {
        sizeText = [NSString stringWithFormat:@"%zdB", size];
    }
    return sizeText;
}

/**
 获取文件夹大小
 */
- (long long)getFileSizeWith:(NSString *)illnessCasePath {
    
    // 创建文件管理对象
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:illnessCasePath error:nil];
    long long cacheSize = 0;
    //遍历所有子文件
    for (NSString *subPath in subPaths) {
        // 拼接完整路径
        NSString *filePath = [illnessCasePath stringByAppendingFormat:@"/%@",subPath];
        // 计算文件的大小
        long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
        // 加载到文件的大小
        cacheSize += fileSize;
    }
    return cacheSize;
}

/**
 移除文件夹
 */
- (void)cleanCacheAtPath:(NSString *)path {
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        [fileManager removeItemAtPath:path error:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
